/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FormSupplier.java
 *
 * Created on Feb 5, 2011, 4:49:03 AM
 */

package juwita;

import config.DBConnection;
import java.sql.*;
//import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JOptionPane;

/**
 *
 * @author Abah
 */
public class FormSupplier extends javax.swing.JInternalFrame {

    private DefaultTableModel DftTabMode;
    java.sql.Connection conn = new DBConnection().connect();
    
    /** Creates new form FormSupplier */
    public FormSupplier() {
        initComponents();
        btnEdit.setEnabled(false);
        btnDelete.setEnabled(false);

        tampilData();
        setKdSup();
        kosongkanNew();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnTengah = new javax.swing.JPanel();
        spSup = new javax.swing.JScrollPane();
        tbSup = new javax.swing.JTable();
        pnAtas = new javax.swing.JPanel();
        btnDelete = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        txtNamaSup = new javax.swing.JTextField();
        txtKdSup = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtAlamat = new javax.swing.JTextArea();
        btnShowAll = new javax.swing.JButton();
        txtSearch = new javax.swing.JTextField();
        btnNew = new javax.swing.JButton();
        cbSearch = new javax.swing.JComboBox();
        btnSearch = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        txtHp = new javax.swing.JTextField();
        txtTelp = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtFax = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();

        setBackground(new java.awt.Color(255, 255, 255));
        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Master Data Supplier");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/mnSupplier.png"))); // NOI18N
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        pnTengah.setBackground(new java.awt.Color(255, 255, 255));
        pnTengah.setLayout(new java.awt.BorderLayout());

        tbSup.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tbSup.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tbSupMousePressed(evt);
            }
        });
        tbSup.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tbSupKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tbSupKeyReleased(evt);
            }
        });
        spSup.setViewportView(tbSup);

        pnTengah.add(spSup, java.awt.BorderLayout.CENTER);

        pnAtas.setBackground(new java.awt.Color(255, 255, 255));
        pnAtas.setPreferredSize(new java.awt.Dimension(410, 280));
        pnAtas.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });
        pnAtas.add(btnDelete, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 130, 70, 20));

        btnEdit.setText("Edit");
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });
        pnAtas.add(btnEdit, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 100, 70, -1));
        pnAtas.add(txtNamaSup, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 40, 300, -1));

        txtKdSup.setEditable(false);
        txtKdSup.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtKdSupKeyReleased(evt);
            }
        });
        pnAtas.add(txtKdSup, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 10, 61, -1));

        jLabel3.setText("Kode Sup");
        pnAtas.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, -1, -1));

        jLabel4.setText("Handphone");
        pnAtas.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 100, -1, -1));

        txtAlamat.setColumns(20);
        txtAlamat.setRows(5);
        jScrollPane1.setViewportView(txtAlamat);

        pnAtas.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 160, 220, 50));

        btnShowAll.setText("Show All");
        btnShowAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnShowAllActionPerformed(evt);
            }
        });
        pnAtas.add(btnShowAll, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 240, 80, -1));
        pnAtas.add(txtSearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 220, 190, -1));

        btnNew.setText("New");
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });
        pnAtas.add(btnNew, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 70, 70, -1));

        cbSearch.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Kode Sup", "Nama" }));
        pnAtas.add(cbSearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 220, 80, -1));

        btnSearch.setText("Search");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });
        pnAtas.add(btnSearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 240, 70, -1));

        jLabel5.setText("Alamat");
        pnAtas.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 160, -1, -1));
        pnAtas.add(txtHp, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 100, 160, -1));
        pnAtas.add(txtTelp, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 70, 160, -1));

        jLabel6.setText("Telp");
        pnAtas.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, -1, -1));

        jLabel7.setText("Nama Sup");
        pnAtas.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, -1, 20));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/supplier.png"))); // NOI18N
        pnAtas.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 180, 100, 80));
        pnAtas.add(txtFax, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 130, 160, -1));

        jLabel8.setText("Fax");
        pnAtas.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 130, -1, -1));

        pnTengah.add(pnAtas, java.awt.BorderLayout.PAGE_START);

        getContentPane().add(pnTengah, java.awt.BorderLayout.CENTER);

        setBounds(0, 0, 426, 454);
    }// </editor-fold>//GEN-END:initComponents

    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        // TODO add your handling code here:
        int clossing;
        clossing = JOptionPane.showConfirmDialog(this,
                "Tutup Data Pemasok?",
                "Konfirmasi",
                JOptionPane.YES_NO_OPTION);
        if (clossing == 0){
            this.dispose();
            FormMain.isfSup = false;
        }
    }//GEN-LAST:event_formInternalFrameClosing

    private void tbSupMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbSupMousePressed
        getDataFromTable();
}//GEN-LAST:event_tbSupMousePressed

    private void tbSupKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbSupKeyPressed
        // TODO add your handling code here:
}//GEN-LAST:event_tbSupKeyPressed

    private void tbSupKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbSupKeyReleased
        // TODO add your handling code here:
        getDataFromTable();
}//GEN-LAST:event_tbSupKeyReleased

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        // TODO add your handling code here:
        if(btnDelete.getText().equals("Cancel")){
            kosongkan();
            tampilData();
        }else if(btnDelete.getText().equals("Delete")){
            deleteData();
        }

        //*
        //*/
}//GEN-LAST:event_btnDeleteActionPerformed

    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
        // TODO add your handling code here:
        //BARU KOPAS
        if(btnEdit.getText().equals("Save")){
            if(txtNamaSup.getText().equals("")) {
                JOptionPane.showMessageDialog(this, "Nama Supplier harus diisi!",
                        "Informasi",JOptionPane.INFORMATION_MESSAGE);
            }else{
                if(txtTelp.getText().equals("") || txtHp.getText().equals("") ) {
                    JOptionPane.showMessageDialog(this, "Kontak no (telp/hp) harus diisi!",
                            "Informasi",JOptionPane.INFORMATION_MESSAGE);
                }else{

                    if(isDuplicatePKey()==true){
                        kosongkanNew();
                        txtNamaSup.requestFocus();
                    }else{
                        insertData();
                    }
                }
            }
        }else if (btnEdit.getText().equals("Edit")){
            editData();
        }

        //*
        //*/
}//GEN-LAST:event_btnEditActionPerformed

    private void txtKdSupKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtKdSupKeyReleased
        // TODO add your handling code here:
}//GEN-LAST:event_txtKdSupKeyReleased

    private void btnShowAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnShowAllActionPerformed
        // TODO add your handling code here:
        tampilData();
        txtSearch.setText("");
}//GEN-LAST:event_btnShowAllActionPerformed

    private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
        // TODO add your handling code here:
        kosongkanNew();
}//GEN-LAST:event_btnNewActionPerformed

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        // TODO add your handling code here:
        tampilTabelSearch();
        kosongkan();
    }//GEN-LAST:event_btnSearchActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnNew;
    private javax.swing.JButton btnSearch;
    private javax.swing.JButton btnShowAll;
    private javax.swing.JComboBox cbSearch;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel pnAtas;
    private javax.swing.JPanel pnTengah;
    private javax.swing.JScrollPane spSup;
    private javax.swing.JTable tbSup;
    private javax.swing.JTextArea txtAlamat;
    private javax.swing.JTextField txtFax;
    private javax.swing.JTextField txtHp;
    private javax.swing.JTextField txtKdSup;
    private javax.swing.JTextField txtNamaSup;
    private javax.swing.JTextField txtSearch;
    private javax.swing.JTextField txtTelp;
    // End of variables declaration//GEN-END:variables



    private void kosongkan(){
        txtNamaSup.setText("");
        txtTelp.setText("");
        txtHp.setText("");
        txtFax.setText("");
        txtAlamat.setText("");
        btnEdit.setEnabled(false);
        btnDelete.setEnabled(false);
        btnEdit.setText("Edit");
        btnDelete.setText("Delete");
    }
    private void kosongkanNew(){
        setKdSup();
        txtNamaSup.setText("");
        txtTelp.setText("");
        txtHp.setText("");
        txtFax.setText("");
        txtAlamat.setText("");
        btnEdit.setText("Save");
        btnDelete.setText("Cancel");
        btnEdit.setEnabled(true);
        btnDelete.setEnabled(true);
    }
    private void tampilData(){
        Object[] Baris={"Kode","Nama"};
        DftTabMode=new DefaultTableModel(null,Baris);
        tbSup.setModel(DftTabMode);

        try {
            java.sql.Statement stmt = conn.createStatement();
            java.sql.ResultSet rslt = stmt.executeQuery("Select * from tsup");
            while (rslt.next()) {
                String sKdSup = rslt.getString("kdSup");
                String sNamaSup = rslt.getString("nmSup");

                String[] dataField = {sKdSup, sNamaSup};
                DftTabMode.addRow(dataField);
            }

        }
        catch(SQLException e) {
            System.out.println("gagal : " + e.toString());
        }
    }

    private void tampilTabelSearch(){

        String srcby = "";
        if(cbSearch.getSelectedItem().toString().equals("Kode Sup")){
            srcby = "kdSup";
        }else{
            srcby = "nmSup";
        }

        Object[] Baris={"Kode","Nama"};
        DftTabMode=new DefaultTableModel(null,Baris);
        tbSup.setModel(DftTabMode);

        try {
            java.sql.Statement stmt = conn.createStatement();
            java.sql.ResultSet rslt = stmt.executeQuery(
                    "SELECT * FROM tsup WHERE UPPER(" + srcby +
                    ") like UPPER('%" +
                    txtSearch.getText() + "%')");

            while (rslt.next()) {
                String sKdSup = rslt.getString("kdSup");
                String sNamaSup = rslt.getString("nmSup");

                String[] dataField = {sKdSup, sNamaSup};
                DftTabMode.addRow(dataField);
            }

        }
        catch(SQLException e) {
            System.out.println("gagal : " + e.toString());
        }
    }
    private void deleteData(){
            try {
                int deleting;
                deleting = JOptionPane.showConfirmDialog(this,
                        "Apakah Anda yakin akan menghapus "

                        //+ cbKodeKota.getSelectedItem().toString() +" "
                        +txtNamaSup.getText() +"?",
                        "Konfirmasi",
                        JOptionPane.YES_NO_OPTION);
                if (deleting == 0){

                    PreparedStatement pStatement = null;
                    String sql = "DELETE FROM tsup " +
                            "WHERE kdSup=? ";
                    pStatement = conn.prepareStatement(sql);

                    pStatement.setString(1, txtKdSup.getText());

                    int intTambah = pStatement.executeUpdate();
                    if (intTambah >0){
                        JOptionPane.showMessageDialog(this,
                                "Delete sukses", "Informasi",
                                JOptionPane.INFORMATION_MESSAGE);

                    }else {
                        JOptionPane.showMessageDialog(this,
                                "Delete gagal", "Informasi",
                                JOptionPane.INFORMATION_MESSAGE);
                    }

                    pStatement.close();

                    kosongkan();
                    tampilData();
                }
            } catch(SQLException e){
                System.out.println("koneksi gagal " + e.toString());
            }
    }
    private boolean isDuplicatePKey(){
        String pKey = txtKdSup.getText();
        boolean result = true;
        int row = 0;

        try {
            java.sql.Statement stmt = conn.createStatement();
            java.sql.ResultSet rslt = stmt.executeQuery("Select * from tsup WHERE kdSup=" +
                    "'" +pKey+ "'");
            while (rslt.next()) {
                row = rslt.getRow();
            }
                if(row > 0){
                    JOptionPane.showMessageDialog(this, "Kode "+pKey+" sudah ada"
                            ,"Peringatan",JOptionPane.WARNING_MESSAGE);
                    result = true;
                }else{
                    result = false;
                }
            System.out.println("row : " + row);
        }
        catch(SQLException e) {
            System.out.println("gagal : " + e.toString());
        }
        return result;
    }
    private void insertData(){
        // panggil method koneksi
        //java.sql.Connection conn = new DBConnection().connect();

        java.sql.PreparedStatement pStatement = null;
        String sql = "INSERT INTO tsup " +
                "(kdSup, nmSup, alamat, tlp, hp, fax, tgl_insert, tgl_update,user_id) " +
                "VALUES (?,?,?,?,?,?,now(),now(),?)";
        try {
            pStatement = conn.prepareStatement(sql);
            pStatement.setString(1, txtKdSup.getText());
            pStatement.setString(2, txtNamaSup.getText());            
            pStatement.setString(3, txtAlamat.getText());
            pStatement.setString(4, txtTelp.getText());
            pStatement.setString(5, txtHp.getText());
            pStatement.setString(6, txtFax.getText());
            pStatement.setString(7, "admin");

            int intTambah = pStatement.executeUpdate();
            if (intTambah>0){
                JOptionPane.showMessageDialog(this,
                        "Penambahan sukses", "Informasi",
                        JOptionPane.INFORMATION_MESSAGE);
            }else{
                JOptionPane.showMessageDialog(this,
                        "Penambahan gagal", "Informasi",
                        JOptionPane.INFORMATION_MESSAGE);
            }
            pStatement.close();
            //conn.close();

            kosongkan();
            tampilData();

        }
        catch(SQLException e){
            System.out.println("koneksi gagal " + e.toString());
        }

    }

     private void editData(){

        try {
            PreparedStatement pStatement = null;
            String sql = "UPDATE tsup " +
                    "SET nmSup=?, alamat=?, tlp=?, hp=?, fax=?, tgl_update=now() " +
                    "WHERE kdSup=? ";
            pStatement = conn.prepareStatement(sql);

            pStatement.setString(1, txtNamaSup.getText());            
            pStatement.setString(2, txtAlamat.getText());
            pStatement.setString(3, txtTelp.getText());
            pStatement.setString(4, txtHp.getText());
            pStatement.setString(5, txtFax.getText());
            pStatement.setString(6, txtKdSup.getText());

            int intTambah = pStatement.executeUpdate();
            if (intTambah >0){
                JOptionPane.showMessageDialog(this,
                        "Edit sukses", "Informasi",
                        JOptionPane.INFORMATION_MESSAGE);

            }else {
                JOptionPane.showMessageDialog(this,
                        "Edit gagal", "Informasi",
                        JOptionPane.INFORMATION_MESSAGE);
            }

            pStatement.close();
            kosongkan();
            tampilData();


        } catch(SQLException e){
            System.out.println("koneksi gagal " + e.toString());
        }
    }
    private void getDataFromTable(){
                // TODO add your handling code here:
        Object oKdSup, oNamaSup;//

        oKdSup = tbSup.getValueAt(tbSup.getSelectedRow(), 0);
        oNamaSup = tbSup.getValueAt(tbSup.getSelectedRow(), 1);


        try {
            java.sql.Statement stmt = conn.createStatement();
            java.sql.ResultSet rslt = stmt.executeQuery("Select * from tsup WHERE kdSup=" +
                    "'" +oKdSup+ "'");
            while (rslt.next()) {
                txtTelp.setText(rslt.getString("tlp"));
                txtHp.setText(rslt.getString("hp"));
                txtFax.setText(rslt.getString("fax"));
                txtAlamat.setText(rslt.getString("alamat"));
            }

        }
        catch(SQLException e) {
            System.out.println("gagal : " + e.toString());
        }

        /*
        if(oTest == null){
            oTest = " ";
        }
         *
         */

        txtKdSup.setText(oKdSup.toString());
        txtNamaSup.setText(oNamaSup.toString());

        btnEdit.setEnabled(true);
        btnDelete.setEnabled(true);
    }

    private void setKdSup(){
        String kdSup = "";
        try {
            java.sql.Statement stmt = conn.createStatement();
            java.sql.ResultSet rslt = stmt.executeQuery(
                    "SELECT * FROM tsup");
            //int iNo = 0;
            while (rslt.next()) {
                int row = rslt.getRow();
                kdSup = rslt.getString("kdSup");
            }
        }
        catch(SQLException e) {
            System.out.println("gagal : " + e.toString());
        }
        if(kdSup.equals("")){
            kdSup = "S0000";
        }

        System.out.println(kdSup);
        kdSup = kdSup.substring(2);
        System.out.println(kdSup);
        int noUrut;
        noUrut = Integer.parseInt(kdSup);
        noUrut++;
        java.text.DecimalFormat nft = new java.text.DecimalFormat("#0000.###");
        nft.setDecimalSeparatorAlwaysShown(false);
        System.out.println("S"+nft.format(noUrut));
        txtKdSup.setText("S"+nft.format(noUrut));
    }
    
}
